<?php
namespace App\Models\Image;
use App\Libs\Base\Constant;
class Image extends \App\Libs\Base\BaseModel
{
    protected $__TABLE__ = 't_paile_image';	


	private function generate($md5) {
		$v = crc32($md5);
		$av = ord('a');
		$paths = array(
			'o',
			chr(intval($v / 26) % 26 + $av),
			chr($v % 26 + $av),
			$md5 . '.jpg',
		);
		return $paths;
	}

	
    public function saveTmp($file) {
		if (empty($file)) {
			return null;
		}
		// phone is not regist
		$tmp = $file->getTempName();
		if (!file_exists($tmp)) {
			return null;
		}
		$md5 = md5_file($tmp);
		$size = getimagesize($tmp);
		$params = array(
			'md5 = ?0',
			'width' => $size[0],
			'height' => $size[1],
			'bind' => array($md5),
		);
		$image = self::find($params);
		if ($image) {
			return $image;
		}
		$paths = $this->generate($md5);

		$uri = '/images/' . implode('/', $paths);

		$fileName = array_pop($paths);
		$path = APP_PATH . 'public' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $paths);
		@mkdir($path, 0755, true);
		// save to dirctory
		$r = $file->moveTo($path . DIRECTORY_SEPARATOR . $fileName);
		$infos = array(
			'md5' => $md5,
			'width' => $size[0],
			'height' => $size[1],
			'size' => $file->getSize(),
			'uri' => $uri,
			'mime' => $size['mime'],
			'ctime' => date('Y-m-d H:i:s'),
		);

		foreach ($infos as $field => $value) {
			$this->{$field} = $value;
		}

		$this->save();

		return $this;
    }
}
